// 拷贝到剪贴板
async function CopyLinkNameandurlToClipboard(text) {
  console.log(text);
  const item = new ClipboardItem({
    "text/html": new Blob([`<a href="${text.url}">${text.name}</a>`], { type: "text/html" }),
    "text/plain": new Blob([text.url], { type: "text/plain" }),
  });
  try {
    await navigator.clipboard.write([item]);
  } catch (err) {
    document.addEventListener("copy", oncopy, true);

    // Requires the clipboardWrite permission, or a user gesture:
    let res = document.execCommand("copy") ? "success" : "fail";
    console.log("navigator.clipboard.write: fail.  document.execCommand: "+res);
  }
  function oncopy(event) {
    document.removeEventListener("copy", oncopy, true);
    // Hide the event from the page to prevent tampering.
    event.stopImmediatePropagation();

    // Overwrite the clipboard content.
    event.preventDefault();
    event.clipboardData.setData("text/plain", text);
  }
}

// 在链接上右键菜单激活时通知后台这个链接的信息，后台能获得url但是得不到text
function notifyClnuExtensionBackgroudjs(e) {
  var ele = e.target;
  if (ele.tagName == "A") {
    browser.runtime.sendMessage({ url: ele.href, name: ele.innerHTML });
  } else if (ele.tagName == "IMG") {
    var url = ele.parentNode.href;
    var name = ele.alt || ele.src;
    browser.runtime.sendMessage({ url: url, name: name });
  }
}

browser.runtime.onMessage.addListener(CopyLinkNameandurlToClipboard);
